/*  
 * cafe-dropdown.js
 * @Author :      PANRUSEN
 * @CreateDate :  2017年6月9日
 * Copyright (c) 2017, NRIET.　
 * TODO
 * 		下拉
 */

;define(function(){
	
	var curMsNum = dateUtil.getCurrentMs();
	
	function getNodeHtml(){
		var wrapper = $('<div class="dropdown">'),
			label = $('<label>'),
			input = $('<input>');
			span = $('<span class="caret">'),
			button = $('<button class="btn dropdown-toggle">'), 
			ul = $('<ul class="dropdown-menu">'),
			id = 'dropdown-' + curMsNum;
		button.attr({
			id: id,
			type: 'button',
			'data-toggle': 'dropdown',
			'aria-haspopup': 'true',
			'aria-expended': 'true'
		}).data('toggle', 'dropdown').append(label).append(span);
		ul.attr({'aria-labelledby': id});
		input.attr({
			type: 'hidden'
		});
		wrapper.append(input).append(button).append(ul);
		return wrapper;
	}
	
	function setConfig($drop, cfs){
		if(!$drop) return;
		var btn = $drop.find('button'), h = btn.height();
		btn.addClass('btn-' + cfs.type).css(cfs.css);
		$drop.find('label').text(cfs.text);
		btn.css({
			'border-radius': cfs.radius
		});
		return $drop;
		
	}
	
	function setDate($drop, data){
		var btn = $drop.find('ul.dropdown-menu'),
			ul = $drop.find('ul'),
			label = $drop.find('label'),
			input = $drop.find('input');
		if(!data){
			return $drop.append($('<li>').html('暂无数据'));
		}
		$.each(data, function(i, dt){
			var li = $('<li>').attr({
				key: dt.id,
				'data-name': dt.name
			}).html(dt.name);
			ul.append(li);
			if(dt.selected){
				label.empty().html(dt.name);
				input.val(dt.id).attr({
					'data-name': dt.name
				}).data('name', dt.name);
			}
		});
		return $drop;
	}
	
	function _eves($drop, cfs){
		var li = $drop.find('ul.dropdown-menu > li'),
			label = $drop.find('label'),
			input = $drop.find('input'),
			btn = $drop.find('button');
		li.on('click' , function(){
			var $zli = $(this);
			label.empty().html($zli.data('name'));
			input.val($zli.attr('key'));
			if(typeof cfs.call === 'function'){
				cfs.call(this, {id:$zli.attr('key'),name:$zli.data('name')});
			}
			btn.blur();
		});
	}
	
	function getVal($drop){
		var input = $drop.find('input');
		return {
			id: input.val(),
			name: input.data('name')
		};
	}
	
	var CFDropdown = function(settings){
		this.$drop = getNodeHtml();
		var options = {
				appendTo: '',
				type: 'primary',				//'default','primary','success','info','warning','danger','link'
				text: 'CFDROPDOWN',
				radius: 2,
				data: null,
				css: {
					padding: '4px 5px',
				    'font-size': '14px',
				}
		};
		this.config = $.extend({},options, settings);
		this.$drop = setConfig(this.$drop, this.config);
		this.$drop = setDate(this.$drop, this.config.data);
		_eves(this.$drop, this.config);
		if(this.config.appendTo){
			$(this.config.appendTo).append(this.$drop);
		}
	}
	
	CFDropdown.prototype = {
			val: function(){
				return getVal(this.$drop);
			}
	};
	
	CafeJS.Dropdown = function(settings){
		var drop =new CFDropdown(settings);
		return drop;
	}
	
	
});